package source

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/astaxie/beego"
)

var (
	Src Source
)

func checkError(err error) {
	if nil != err {
		panic(err)
	}
}

type Source struct {
	data map[string]interface{}
}

func (s *Source) Init(file string) {
	env_str, err := ioutil.ReadFile(file + "/env.json")
	checkError(err)
	var env_json map[string]string
	err = json.Unmarshal(env_str, &env_json)
	env := env_json["env"]
	checkError(err)
	beego.Info("当前环境: " + env)
	data_str, err := ioutil.ReadFile(file + "/hosts.json")
	checkError(err)
	var data map[string]interface{}
	err = json.Unmarshal(data_str, &data)
	checkError(err)
	s.data = data[env].(map[string]interface{})
}

func (s Source) GetMysqlConnStr() string {
	m := s.data["mysql"].(map[string]interface{})
	result := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", m["usr"], m["pwd"], m["ip"], m["port"], m["db"], m["charset"])
	beego.Info(result)
	return result
}

func (s Source) GetEsInfo() map[string]string {
	e := s.data["es"].(map[string]interface{})
	var result = map[string]string{
		"ip":   e["ip"].(string),
		"port": e["port"].(string),
		"usr":  e["usr"].(string),
		"pwd":  e["pwd"].(string),
	}
	return result
}

func (s Source) GetRedisInfo() map[string]string {
	r := s.data["redis"].(map[string]interface{})
	var result = map[string]string{
		"ip":   r["ip"].(string),
		"port": r["port"].(string),
		"pwd":  r["pwd"].(string),
	}
	return result
}

func (s Source) GetFlaskUrl() string {
	f := s.data["flask"].(map[string]interface{})
	url := fmt.Sprintf("http://%s:%s", f["ip"], f["port"])
	return url
}

func (s Source) GetEsUrl() string {
	f := s.data["es"].(map[string]interface{})
	url := fmt.Sprintf("http://%s:%s", f["ip"], f["port"])
	return url
}

func init() {
	workDirectory, _ := os.Getwd()
	// workDirectory = "/home/sivan/0_0/projects/gitee/sivan/beego" // go test 单元测试用
	beego.Info("工作目录: ", workDirectory)
	Src.Init(workDirectory + "/comm/source")
}
